<template>
  <section class="flex flex-col h-full flex-1 overflow-auto">
    <ContentWrap class="relative">
      <div class="flex items-center justify-between mb-0">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="交易时间" prop="orderPeriod">
            <el-date-picker
              v-model="orderPeriod"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="form-item-height"
              end-placeholder="结束时间"
              start-placeholder="开始时间"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="交易类型" prop="transactionType">
            <el-select clearable v-model="queryParams.transactionType" placeholder="请选择交易类型" class="!w-200px">
              <el-option
                v-for="dict in getJLDictOptions(DICT_TYPE.TOP_UP_AND_DEDUCT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="absolute top-4 right-4 mt-2 mr-4">
          <el-button type="primary" plain @click="goBack(0)">
            <Icon icon="ep:back" class="mr-5px"/>
            返回
          </el-button>
        </div>
      </div>
    </ContentWrap>
    <div class="flex justify-between mb-16px" style="background-color: rgba(64,158,254,0.10);height: 40px; border-radius: 8px;">
      <div class="flex items-center" style="margin-left: 40px">
        <span class="font">充值金额</span>
        <span class="text-blue-500 ml-5 font-bold">￥{{ formatAmount(amountList.rechargeAmount) }}</span>
        <span class="font" style="margin-left: 50px">扣款金额</span>
        <span class="text-blue-500 ml-5 font-bold">￥{{ formatAmount(amountList.deductionAmount) }}</span>
      </div>
      <div>
        <el-button @click="toggle">
          <el-tooltip effect="dark" content="全屏" placement="top-start">
            <div style="width: 22px;height: 22px;">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M8 3V5H4V9H2V3H8ZM2 21V15H4V19H8V21H2ZM22 21H16V19H20V15H22V21ZM22 9H20V5H16V3H22V9Z"></path>
              </svg>
            </div>
          </el-tooltip>
        </el-button>
      </div>
    </div>
    <el-table class="flex-1" ref="singleTableRef" v-loading="loading" :data="list" border stripe
              :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
              height="100%">
      <el-table-column type="index" width="55" fixed="left"/>
      <el-table-column label="所属企业" align="left" prop="tenantName" min-width="150"/>
      <el-table-column label="客户企业" align="left" prop="customerName" min-width="150"/>
      <el-table-column label="账户类型" align="left" prop="accountType" min-width="150">
        <template #default="{ row }">
          <StatusText class="status-text" :type="DICT_TYPE.ACCOUNT_TYPE" :value="row.accountType"></StatusText>
        </template>
      </el-table-column>
      <el-table-column label="交易类型" align="left" prop="transactionType" min-width="150">
        <template #default="{ row }">
          <StatusText class="status-text" :type="DICT_TYPE.TOP_UP_AND_DEDUCT" :value="row.transactionType"></StatusText>
        </template>
      </el-table-column>
      <el-table-column label="交易金额" align="left" prop="transactionAmount" min-width="150">
        <template #header>
          <el-container class="flex items-center">
            <span>交易金额</span>
            <el-tooltip effect="dark" content="红色金额可点击查看详情" placement="top-start">
              <el-icon :color="'#8fbff3'" :size="20" class="ml-4px">
                <WarningFilled/>
              </el-icon>
            </el-tooltip>
          </el-container>
        </template>
        <template #default="{ row }">
        <span
          :style="{
            color: getBalanceColor(row),
            cursor: row.transactionType === 1 ? 'pointer' : 'default',
            textDecoration: row.transactionType === 1 ? 'underline' : 'none'
          }"
          @click="row.transactionType === 1 && row.waybillId && showDetailDialog(row)"
        >
        {{ formatBalance(row) }}
      </span>
        </template>
      </el-table-column>
      <el-table-column label="账户余额" align="left" prop="accountBalance" min-width="150"/>
      <el-table-column label="备注" align="left" prop="remark" min-width="150"/>
      <el-table-column label="交易时间" align="left" prop="transactionTime" min-width="150" :formatter="dateFormatter"/>
    </el-table>
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
                @pagination="getList" />
  </section>
  <el-dialog v-model="dialogVisible" title="扣款明细" width="540">
    <div class="dialog-content">
        <div class="dialog-item">
          <span class="dialog-label">客户企业</span>
          <span class="dialog-value">{{ selectedRow.customerName || ''}}</span>
        </div>
        <div class="dialog-item">
          <span class="dialog-label">产品名称</span>
          <span class="dialog-value">{{ selectedRow.productName || ''}}</span>
        </div>
        <div class="dialog-item">
          <span class="dialog-label">司机姓名</span>
          <span class="dialog-value">{{ selectedRow.driverName || ''}}</span>
        </div>
        <div class="dialog-item">
          <span class="dialog-label">身份证号</span>
          <span class="dialog-value">{{ selectedRow.driverIdNo || ''}}</span>
        </div>
        <div class="dialog-item">
          <span class="dialog-label">车牌号</span>
          <span class="dialog-value">{{ selectedRow.vehicleNo || ''}}</span>
        </div>
      <div class="dialog-item">
        <span class="dialog-label">成交单价</span>
        <span class="dialog-value1">{{ selectedRow.endPrice || ''}}<span class="dialog-unit">元/吨</span></span>
      </div>
      <div class="dialog-item">
        <span class="dialog-label">成交总价</span>
        <span class="dialog-value1">{{ selectedRow.priceTotal || ''}}<span class="dialog-unit">元</span></span>
      </div>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import {DICT_TYPE, getIntDictOptions, getJLDictOptions} from '@/utils/dict'
import {useFullscreen} from "@vueuse/core";
import * as individualAccountManageApi from "@/api/individualAccount";
import * as salesWaybillApi from "@/api/salesWaybill";

const orderPeriod = ref([])
const singleTableRef = ref()
const {isFullscreen, toggle} = useFullscreen(singleTableRef)
const formRef = ref()
const {t} = useI18n()
const message = useMessage()
const formLoading = ref(false)
const emit = defineEmits(['subPage'])
const queryFormRef = ref()
const total = ref(0)
const list = ref([])
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  transactionTime: [],
  transactionType: undefined,
  oneYearAcceptanceAccountId: undefined,
})
const props = defineProps<{
  rowData?: object
}>()

const getBalanceColor = (row) => {
  if (row.transactionType === 0) {
    return '#2c952c';
  } else if (row.transactionType === 1) {
    if (row.waybillId) {
      return 'red';
    } else {
      return '#ff9900';
    }
  }
  return '#000000';
};
// 根据交易类型决定显示金额的正负值
const formatBalance = (row) => {
  const transactionType = row.transactionType;

  const value = parseFloat(row.transactionAmount) || 0;
  return transactionType === 0 ? `+${value.toFixed(2)}` : `-${value.toFixed(2)}`;
};

const getList = async () => {
  formLoading.value = true
  if (orderPeriod.value && orderPeriod.value.length > 1) {
    queryParams.value.transactionTime = [orderPeriod.value[0], orderPeriod.value[1]]
  } else {
    queryParams.value.transactionTime = undefined
  }
  try {
    const res = await individualAccountManageApi.getDispatchTransactionRecordPage(queryParams.value)
    total.value = res?.total || 0
    list.value = res.list || []
  } finally {
    formLoading.value = false
  }
  getDispatchTransactionRecordTotal()
}

const amountList = ref([])
const getDispatchTransactionRecordTotal = async () => {
  const res = await individualAccountManageApi.getDispatchTransactionRecordTotal(queryParams.value)
  amountList.value = res || []
}

const formatAmount = (amount) => {
  if (amount === null || amount === undefined) {
    return '0.00';
  }
  const num = parseFloat(amount);
  if (isNaN(num)) {
    return '0.00';
  }
  return num.toFixed(2).replace(/\B(?=(\d{4})+(?!\d))/g, ',');
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.value.transactionTime = undefined
  orderPeriod.value = []
  handleQuery()
}

const goBack = (index: number) => {
  emit('subPage', index)
}

const dialogVisible = ref(false);
const selectedRow = ref(null);
const showDetailDialog = async(row) => {
  const res = await salesWaybillApi.getInfoById({id: row.waybillId})
  selectedRow.value = res || {};
  dialogVisible.value = true;
};

// 初始化查询参数
const initializeQueryParams = () => {
  const {rowData} = props
  queryParams.value = {
    ...queryParams.value,
    customerId: rowData.id,
    cashAccountId: rowData.cashAccountId,
    acceptanceAccountId: rowData.acceptanceAccountId,
    oneYearAcceptanceAccountId: rowData.oneYearAcceptanceAccountId
  }
}

onMounted(() => {
  initializeQueryParams()
  getList()
})
</script>
<style lang="scss" scoped>
:deep(.el-dialog) {
  .el-dialog__header {
    text-align: center; // 标题居中

    .el-dialog__title {
      font-weight: bold;
    }
  }

  .el-dialog__body {
    padding: 20px 40px; // 增加整体内边距
  }
}

.dialog-content {
  .dialog-item {
    display: flex;
    margin-bottom: 16px;
    text-align: left;
    margin-left: 40px;

    .dialog-label {
      width: 80px;
      flex-shrink: 0;
      font-weight: bold;
      color: #909399;
      font-family: PingFang SC, PingFang SC-400;
      display: inline-block;
      text-align-last: justify; // 使用text-align-last实现两端对齐
      margin-right: 10px;
      &::after {
        content: "：";
        color: #909399;
      }
    }

    .dialog-value {
      flex: 1;
      font-family: PingFang SC, PingFang SC-400;
      font-weight: 400;
      color: #303133;
    }

    .dialog-value1 {
      @extend .dialog-value;
      font-weight: bold;
      font-size: 18px;
    }
    .dialog-unit {
      @extend .dialog-value;
      margin-left: 5px; // 与数值保持一点间距
      font-size: 14px;
    }
  }
}
.font {
  font-size: 14px;
  font-family: Helvetica Neue, Helvetica Neue-400;
  font-weight: 400;
  color: #303133;
}
.status-text{
  padding: 4px 0px !important;
}
</style>
